package com.plumelog.lite.config;

import com.alibaba.fastjson.JSONObject;
import com.plumelog.lite.controller.Result;
import org.springframework.http.HttpMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * @Auther: duanhong
 * @Date: 2022/6/4 15:15
 */
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {


        HttpServletRequest request = ( HttpServletRequest ) servletRequest;
        HttpServletResponse response = ( HttpServletResponse ) servletResponse;

        String url = request.getRequestURI();
        if (url.contains("logout") || url.contains("login")) {
            chain.doFilter(request, response);
            return;
        }

        if (!Objects.equals(request.getMethod(), HttpMethod.POST.name())) {
            chain.doFilter(request, response);
            return;
        }
//        if (StringUtils.isEmpty(InitConfig.loginUsername)) {
//            chain.doFilter(request, response);
//            return;
//        }
        Object token = request.getSession().getAttribute("token");
        if (token == null) {
            printMessage(response, Result.UN_LOGIN);
            return;
        }
        chain.doFilter(request, response);
    }


    private void printMessage(HttpServletResponse response, Result rm) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(JSONObject.toJSONString(rm));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
